<?php
namespace app\home\controller;
use app\common\validate\reg;
use think\Controller;
use think\Db;
use app\home\model\Mumber;
use think\Cache;
use app\home\controller\Redis_self;
use Elasticsearch\ClientBuilder;
/*use redis\RedisCluster as Redispake;*/
ini_set('default_socket_timeout', -1);
class Login extends Controller
{
    private $client;
    public $out_time=30;
    public $redis;
    public static $instance;
 public function _initialize()
 {
   $this->redis=Cache::store('redis')->handler();
    $params = array(
            '127.0.0.1:9200'
        );
        /*$this->client = ClientBuilder::create()->setHosts($params)->build();*/
 }

    public function index()
    {
  /*      dump(Mumber::mumberTrade());*/
      /*  $res=$this->redis->get('user');*/

         /*  Db::name('mumber')->where('uid',3)->find();*/
       /* Db::startTrans();
        try{
              $info = Db::name('mumber')->where('uid',3)->lock(true)->find();
            
            Db::commit();
               echo 'success';
        }catch(\Exception $e){
            Db::rollback();
             echo 'fail';
        }*/
        if(session('user_id')){
            $this->redirect('Index/index');
        }
        if(request()->isAjax()){
            $User = db('mumber')
                ->where('username',input('post.username'))
                ->where('password',md5(input('post.password')))
                ->find();
            if(empty($User)){
                return ['row'=>0,'fonts'=>'账号或者密码错误！'];
            }else{
                $time=time();
                session('user_id',$User['uid']);
                session('token',$time);
                db('mumber')
                    ->where('uid',$User['uid'])
                    ->setField('token',$time);
                db('mumber')
                    ->where('uid',$User['uid'])
                    ->setField('logintime',time());
                db('mumber')
                    ->where('uid',$User['uid'])
                    ->setField('ip',$_SERVER["REMOTE_ADDR"]);
                return ['row'=>1,'fonts'=>'登陆成功！'];
            }
        }
        return view();
    }


    public function get_data(){
 /*      $info = Db::name('mumber')->where('uid',3)->find();*/
     /*  var_dump($info);
       die;*/$this->redis->set('user',60,30);
        //队列获取消息
         /* while(1) {
                     $value = $this->redis->lpop('test');
                     if($value){
                         dump($value);
                        break;
                     }
                    }*/

    }





  //接受者1
    /*order是订阅的发布者 可以有多个
     *$redis 是redis实例
     * $chan 是channel
     * $msg 是订阅者的消息
     * */
    public function redis_sub(){
     
            //创建频道order
            $res=$this->redis->subscribe(['tests'], function ($redis, $chan, $msg) {
                var_dump($redis);
                var_dump($chan);
                var_dump($msg);
           
            });
    
    }

/*发布者
 *order 是发布者
 * 第二个参数是发布的信息
 * */
    public function redis_pub(){
      $order = [
            'msg' => '夏天有你真好',
        ];

        $res=$this->redis->publish("tests", json_encode($order));
    
    }




























    public function GetUserIP(){
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
            //为了兼容百度的CDN，所以转成数组
            $arr = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
            return $arr[0];
        }else{
            return $_SERVER['REMOTE_ADDR'];
        }
    }
    //验证码

    public function register()
    {

        if(request()->isAjax())
        {
            $data = input('post.');
            $data['fid'] = input('fid');

            //验证传入值
            $validate = new reg();
            if (!$validate->check($data)) {
                return ['row' => 0, 'fonts' => $validate->getError()];
            }
            //if(db('mumber')->where('zhuce_ip', $_SERVER["REMOTE_ADDR"])->count()){
            //return ['row' => 0, 'fonts' => '同ip只能注册一个账号！'];
            //};
            //验证
            if (!captcha_check($data['code'])){
                return ['row' => 0, 'fonts' => '验证码错误'];
            }
            //检查号码是否存在
            if(Db::name('mumber')->where('username',$data['username'])->count())
            {
                return ['row' => 0, 'fonts' => '手机号已存在'];
            }
            //检查支付宝是否存在
            if(Db::name('mumber')->where('pay',$data['pay'])->count()>2)
            {
                return ['row' => 0, 'fonts' => '支付宝超出绑定'];
            }

            //增加新数据
            $data['datetime'] = time();
            $data['password'] = md5($data['password']);
            //$data['putpassword'] = md5($data['password']);
            $data['zhuce_ip']=$this->GetUserIP();
            $data['ip']=$_SERVER["REMOTE_ADDR"];
            $time=time();
            $data['token']=$time;
            //开启事务
            unset($data['passwords']);
            unset($data['code']);
            //数据增加
            $id = Db::name('mumber')->insertGetId($data);
            //创建团队
            Db::name('mumber_team')->insert(['uid'=>$id]);

            $val=Db::name('mumber')->where('uid',$id)->find();
            session('user_id',$id);
            session('token',$time);
            $free_msg=Db::name('control')->where('id',1)->value('free_order');

            if($free_msg=='1'){
                //时间段免费赠送
                $free_data=[
                    'uid'=>$id,
                    'price'=>97,
                    'p_num'=>20,
                    'p_nums'=>20,
                    'p_price'=>6,
                    'b_datetime'=>time(),
                    'b_status'=>0,
                    'trade'=>"FREE_".time().rand(111,999),
                    'up_time'=>time(),
                    'b_buy'=>1
                ];
                Db::name('buy')->insert($free_data);
            }
            return ['row'=>1,'fonts'=>'注册成功！'];

        }
        //推荐人不得为后台管理员
        if(input('fid')==1){
            $this->error('未查询到您的推荐人');
        }
        $f_status=Db::name('mumber')->where('uid',input('fid'))->value('status');
        if($f_status===null){
            $this->error('未查询到您的推荐人');
        }
        /* if($f_status===0){
           $this->error('您的推荐人未完成首次购买');
         }*/
        return view();
    }
    public function xiazai(){
        return view();
    }
}